package com.shansun.event
import scala.reflect.BeanProperty
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import scala.collection.JavaConversions

/**
 * Event engine, to start, register processors, etc
 * @author:     lanbo <br>
 * @version:    1.0  <br>
 * @date:   	2012-4-10
 */
object EventEngine {

    val log: Logger = LoggerFactory.getLogger(EventEngine.getClass())

    /**
     * Event persistent, need users to set it, by default, do nothing
     */
    @BeanProperty var persistent: EventPersistent = NoneEventPersistent()

    /**
     * event processors
     */
    var processors = new scala.collection.mutable.HashMap[String, scala.collection.mutable.Set[EventProcessor]]

    def start() = {
        log warn "Starting event engine..."

        EventActor //init Actor
    }

    def stop() = {
        EventActor emit EventType.STOP
    }

    def register(processor: EventProcessor): Unit = {
        val set = processors.getOrElse(processor.getEventType(), new scala.collection.mutable.HashSet[EventProcessor])
        processors += (processor.getEventType() -> (set + processor))
    }

    def unregister(processor: EventProcessor): Unit = {
        val set = processors.getOrElse(processor.getEventType(), null)
        if (set != null) {
            set -= processor
            processors(processor.getEventType()) = set
        }
    }

    def getProcessors(): Map[String, Set[EventProcessor]] = {
        processors.map(kv => (kv._1, kv._2.toSet)).toMap
    }

    def getProcessors(eventType: String): java.util.Set[EventProcessor] = {
        JavaConversions.asJavaSet(processors.getOrElse(eventType, null))
    }
}